import earcut from "./earcut.js";
//多边形面积(vec3)
export function calcArea(pointArray) {
    let indices = triangulation(pointArray);
    let s = 0;
    for (let i = 0; i < indices.length; i += 3) {
        let idx1 = indices[i];
        let idx2 = indices[i + 1];
        let idx3 = indices[i + 2];
        let point1 = pointArray[idx1];
        let point2 = pointArray[idx2];
        let point3 = pointArray[idx3];
        let edge1 = calEdge(point1, point2);
        let edge2 = calEdge(point2, point3);
        let edge3 = calEdge(point3, point1);
        s += calHeron(edge1, edge2, edge3);
    }
    return s;
}

//分割多边形,用耳切法生成索引
export function triangulation(pointArray) {
    let vec3 = [];
    for (let i = 0; i < pointArray.length; i++) {
        vec3.push(pointArray[i].x);
        vec3.push(pointArray[i].y);
        vec3.push(pointArray[i].z);
    }
    let originIndices = earcut(vec3, null, 3);
    let indices = new Uint16Array(originIndices.length);
    for (let i = 0; i < originIndices.length; i++) {
        indices[i] = originIndices[i];
    }
    return indices;
}

//计算两点边长(vec3)
export function calEdge(pointA, pointB) {
    let x2 = Math.pow(pointA.x - pointB.x, 2);
    let y2 = Math.pow(pointA.y - pointB.y, 2);
    let z2 = Math.pow(pointA.z - pointB.z, 2);
    return Math.sqrt(x2 + y2 + z2);
}

//海伦公式（三边长求三角形面积）
export function calHeron(a, b, c) {
    let p = (a + b + c) / 2;
    return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}

//余弦定理（三边长求a角度）
export function cosine(a, b, c) {
    let radian = Math.acos((b * b + c * c - a * a) / (2 * b * c));
    let angle = 180 / (Math.PI / radian);
    return angle;
}

//空间点是否在三角形内(向量叉乘法)
export function isPointInTriangle(P, [A, B, C]) {
    let PA = Li.Vector3.subtract(A, P);
    let PB = Li.Vector3.subtract(B, P);
    let PC = Li.Vector3.subtract(C, P);
    let n1 = Li.Vector3.cross(PA, PB).z;
    let n2 = Li.Vector3.cross(PB, PC).z;
    let n3 = Li.Vector3.cross(PC, PA).z;
    let flag = n1 * n2 >= 0 && n1 * n3 >= 0 && n2 * n3 >= 0;
    return flag;
}

//空间点是否在在多边形内
export function isPointInPolygon(target, pointArray, indices) {
    indices = indices ? indices : triangulation(pointArray);
    let flag = false;
    for (let i = 0; i < indices.length; i += 3) {
        let idx1 = indices[i];
        let idx2 = indices[i + 1];
        let idx3 = indices[i + 2];
        let point1 = pointArray[idx1];
        let point2 = pointArray[idx2];
        let point3 = pointArray[idx3];
        flag = isPointInTriangle(target, [point1, point2, point3]);
        if (flag) {
            break;
        }
    }
    return flag;
}
